package {
	import flash.events.*;
	import flash.media.Video;
	import flash.net.*;
	
	import org.flixel.*;
	
	public class UberAwesomeVideo extends FlxState
	{
		
		protected var timer:Number;
		protected var level:int;
		protected var video:Video;
		protected var stream_ns:NetStream;
		protected var connect_nc:NetConnection;
		public function UberAwesomeVideo(l:int)
		{
			super();
			video = new Video(700, 640);
			level = l;
			timer = 0;
			connect_nc= new NetConnection();
			connect_nc.connect(null);
			stream_ns = new NetStream(connect_nc);
			stream_ns.client = new Object();
			stream_ns.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
			stream_ns.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
			FlxG.stage.addChild(video);
			//video.attachNetStream(stream_ns);
			stream_ns.play("http://games.cs.washington.edu/capstone/11sp/elemental/intro.MP4", 0, 31);
			stream_ns.pause();
		}
		
		public function play():void {
			//stream_ns.client = this;
			//stream_ns.play("http://games.cs.washington.edu/capstone/11sp/elemental/intro.MP4", 0, 31);
			video.attachNetStream(stream_ns);
			stream_ns.resume();
		}
		
		private function netStatusHandler(p_evt:NetStatusEvent):void
		{
			if(p_evt.info.code == "NetStream.Play.FileStructureInvalid")
			{
				trace("The MP4's file structure is invalid.");
			}
			else if(p_evt.info.code == "NetStream.Play.NoSupportedTrackFound")
			{
				trace("The MP4 doesn't contain any supported tracks");
			}
		}
		
		private function asyncErrorHandler(event:AsyncErrorEvent):void {
			trace(event.text);
		}
		
		public override function update():void {
			if (timer == 0) play();
			timer += FlxG.elapsed;
			if (timer > 1) {
				FlxG.stage.addEventListener(MouseEvent.CLICK, dieVideoDIE);
			}
			if (timer > 32) {
				
				FlxG.stage.removeEventListener(MouseEvent.CLICK, dieVideoDIE);
				stream_ns.close();
				connect_nc.close();
				FlxG.stage.removeChild(video);
				FlxG.switchState(new MenuState());
			}
		}
		
		private function dieVideoDIE(e:MouseEvent):void {
			FlxG.stage.removeEventListener(MouseEvent.CLICK, dieVideoDIE);
			
			stream_ns.close();
			connect_nc.close();
			FlxG.stage.removeChild(video);
			FlxG.switchState(new MenuState());
		}
	}
}